package com.ocom.payhandle.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ocom.common.constant.PayHandleUrl;
import com.ocom.common.entity.access.EntityDeptInfo;
import com.ocom.common.entity.card.*;
import com.ocom.common.entity.company.EntityCompanyInfo;
import com.ocom.common.entity.human.EntityPersonnelInfo;
import com.ocom.common.entity.human.EntityRoommateInfo;
import com.ocom.common.entity.master.EntityEcardRegCode;
import com.ocom.common.entity.master.EntityWechatAppInfo;
import com.ocom.common.entity.payconfig.EntityXfDeviceMealConfig;
import com.ocom.common.enums.ResultEnum;
import com.ocom.common.request.payhandle.*;
import com.ocom.common.request.simple.SmsRequest;
import com.ocom.common.resp.Result;
import com.ocom.common.utils.CommonUtil;
import com.ocom.common.utils.DateUtils;
import com.ocom.common.utils.ResultUtil;
import com.ocom.common.utils.wx.WxGhUtils;
import com.ocom.common.vo.devicehttp.MachMealDataVo;
import com.ocom.common.vo.pyhandle.FeePlanVo;
import com.ocom.payhandle.feign.MqSimpleFeign;
import com.ocom.payhandle.feign.PayConfigClientService;
import com.ocom.payhandle.fun.PayFunService;
import com.ocom.payhandle.fun.PayHandleFunService;
import com.ocom.payhandle.service.*;
import com.ocom.redis.util.RedisUtil;
import com.tencent.wmpf.activate.util.WmpfDeviceSignUpUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @Description: 视频通话
 * @Author: 朱晖
 * @Date: 2023/4/26
 **/
@Slf4j
@RestController
public class VideoController {

    @Autowired
    private MqSimpleFeign mqSimpleFeign;

    @Autowired
    private CompanyInfoService companyInfoService;

    @Autowired
    private PersonnelInfoService personnelInfoService;

    @Autowired
    private EcardRegCodeService ecardRegCodeService;

    @Autowired
    private RoommateInfoService roommateInfoService;

    @Autowired
    private XfCardInfoService xfCardInfoService;

    @Autowired
    private XfGoodsListProcessService xfGoodsListProcessService;

    @Autowired
    private XfAccountInfoService xfAccountInfoService;

    @Autowired
    private DeptInfoService deptInfoService;

    @Autowired
    private XfRecordProcessService xfRecordProcessService;

    @Autowired
    private XfDiscountConfigServcie xfDiscountConfigServcie;

    @Autowired
    private ConsTypeConfigService consTypeConfigService;

    @Autowired
    private XfSubAccountListService xfSubAccountListService;

    @Resource
    private RedisUtil redisUtil;

    @Autowired
    PayHandleFunService payHandleFunService;

    @Autowired
    PayFunService payFunService;

    @Autowired
    XfRepairpayConfigService xfRepairpayConfigService;

    @Autowired
    XfRecordWaitpayService xfRecordWaitpayService;

    @Autowired
    PayConfigClientService payConfigClientService;

    @Autowired
    WechatAppInfoService wechatAppInfoService;

    /**
     * 2.12.1 设备上传人脸注册信息（RegisterInf）
     */
    @PostMapping(value = PayHandleUrl.URL_PayHandle_RegisterInf)
    public Result registerInf(@RequestBody RegisterPersonRequest request) {
        EntityPersonnelInfo personnelInfo = new EntityPersonnelInfo();
        personnelInfo.setPPhone(request.getPhone());
        personnelInfo.setPCode(request.getPhone());
        personnelInfo.setPName(request.getPhone());
        personnelInfo.setPPhotoUrl(request.getUrl());
        personnelInfo.setPPhotoUrl2(request.getUrl());
        personnelInfo.setComId(request.getCompanyId());
        personnelInfo.setPType(99l);
        EntityPersonnelInfo entityPersonnelInfo = personnelInfoService.addPerson(request.getCompanyId(), personnelInfo);
        if (entityPersonnelInfo == null) return ResultUtil.error(ResultEnum.Err_2016);

        EntityRoommateInfo entityRoommateInfo = new EntityRoommateInfo();
        entityRoommateInfo.setComId(request.getCompanyId());
        entityRoommateInfo.setType("注册");
        entityRoommateInfo.setName("注册");
        entityRoommateInfo.setPId(entityPersonnelInfo.getPId());
        entityRoommateInfo.setPhone(request.getPhone());
        entityRoommateInfo.setUrl(request.getUrl());
        roommateInfoService.AddRoommate(request.getCompanyId(), entityRoommateInfo);

        EntityXfAccountInfo entityXfAccountInfo = new EntityXfAccountInfo();
        entityXfAccountInfo.setComId(request.getCompanyId());
        entityXfAccountInfo.setPId(entityPersonnelInfo.getPId());
        entityXfAccountInfo.setAccTypeId(1);
        entityXfAccountInfo.setAccountState(0);
        mqSimpleFeign.AddXFAccount(entityXfAccountInfo);
        return ResultUtil.success(entityPersonnelInfo.getPId());
    }

    /**
     * 2.12.2 发送短信接口（SendSMS）
     */
    @PostMapping(value = PayHandleUrl.URL_PayHandle_SendSMS)
    public Result sendSMS(@RequestBody InvitedSmsRequest smsRequest) {

        EntityCompanyInfo entityCompanyInfo = companyInfoService.GetCompanyInfo(smsRequest.getComId());
        if (entityCompanyInfo == null) {
            return ResultUtil.error(ResultEnum.Err_301);
        }

        EntityPersonnelInfo entityPersonnelInfo = personnelInfoService.selectPersonnel(smsRequest.getComId(), smsRequest.getPId());
        if (entityPersonnelInfo == null) {
            return ResultUtil.error(ResultEnum.Err_303);
        }
        SmsRequest request = new SmsRequest();

        request.setSecretId("AKIDcLzhN0a8e8eChEnaQG8zpifcabfnu5JX");
        request.setSecretKey("Kh6VozznPn13ECwSlphN9jCVaRLTPIPa");
        request.setSignName("鑫澳康科技");
        request.setPhone(smsRequest.getPhone());
        request.setSdkAppId("1400314290");
        if (smsRequest.getFlag() == 0) {
            EntityEcardRegCode entityEcardRegCode = new EntityEcardRegCode();
            entityEcardRegCode.setComId(entityCompanyInfo.getComId());
            entityEcardRegCode.setPId(smsRequest.getPId());
            EntityEcardRegCode ecardRegCode = ecardRegCodeService.addRegCodeInfo(entityEcardRegCode);
            if (ecardRegCode == null) return ResultUtil.error(ResultEnum.Err_3077);
            request.setTemplateId("1778075");
            request.getParams().add(entityCompanyInfo.getComName());
            request.getParams().add("XX班");
            request.getParams().add("百里物联");
            request.getParams().add(ecardRegCode.getRegCode());
        } else {
            request.setTemplateId("1778085");
            request.getParams().add(entityCompanyInfo.getComName());
            request.getParams().add("XX班");
            request.getParams().add(entityPersonnelInfo.getPName());
        }
        try {
            mqSimpleFeign.FySms(request);
        } catch (Exception e) {
            log.info("发送短信异常 【{}】", e);
        }
        return ResultUtil.success();
    }


    /**
     * 2.3.4D 保存消费记录-补缴、子账户（saveXfRecordD）
     */
    @PostMapping(value = PayHandleUrl.URL_saveXfRecordD)
    public Result saveXfRecordD(@RequestBody TradeRecordRequest request) {
        EntityXfRecordProcess entityXfRecordProcess = new EntityXfRecordProcess();
        String orderNo = "LX" + request.getTradeNo();
        entityXfRecordProcess.setOrderNo(orderNo);
        entityXfRecordProcess.setComId(request.getCompanyId());
        try {
            String tradeNoRedis = "TradeRecord:" + request.getCompanyId() + ":" + request.getMachNo() + ":" + orderNo;
            if (!redisUtil.lock(tradeNoRedis, 60 * 60)) {
                //订单号重复
                return ResultUtil.success("订单号重复");
            }
            Long pId =  0l;
            EntityPersonnelInfo entityPersonnelInfo = null;
            EntityXfAccountInfo entityXfAccountInfo = null;
            if(request.getType()==1 || request.getType() == 4 || request.getType() == 3){
                pId = request.getUserId();
                entityPersonnelInfo = personnelInfoService.selectPersonnel(request.getCompanyId(), pId);
                entityXfAccountInfo = xfAccountInfoService.selectAccountPid(request.getCompanyId(), pId);
            }
            if(request.getType()==22){
                entityPersonnelInfo = personnelInfoService.getPersonByPCode(request.getCompanyId(), request.getUId());
                if(entityPersonnelInfo!=null){
                    entityXfAccountInfo = xfAccountInfoService.selectAccountPid(request.getCompanyId(), entityPersonnelInfo.getPId());
                }
                entityXfRecordProcess.setCardNo(request.getFaceToken());
            }
            entityXfRecordProcess.setPId(pId);
            entityXfRecordProcess.setMonthValue(request.getTradeTime().replace("-", "").substring(0, 6));
            entityXfRecordProcess.setCreateTime(new Date());
            //1-刷卡，4-刷脸， 3-ocom离线码
            if (request.getType() == 1) {
                entityXfRecordProcess.setOpType(1l);
                entityXfRecordProcess.setOpTypeDiff(100l);
            } else if (request.getType() == 4) {
                entityXfRecordProcess.setOpType(22l);
                entityXfRecordProcess.setOpTypeDiff(100l);
            } else if (request.getType() == 3) {
                entityXfRecordProcess.setOpType(21l);
                entityXfRecordProcess.setOpTypeDiff(100l);
            } else if (request.getType() == 25) {
                entityXfRecordProcess.setOpType(25l);
                entityXfRecordProcess.setOpTypeDiff(100l);
            }
            String cardNo = "";
            EntityCardInfo entityCardInfo = null;
            try {
                entityCardInfo = xfCardInfoService.selectCardByPid(request.getCompanyId(), pId);
                if (entityCardInfo != null && entityCardInfo.getCardState() < 2) {
                    cardNo = entityCardInfo.getCardNo();
                }
            } catch (Exception e) {
                log.info("离线记录-查卡号异常 【{}】", e);
            }
            entityXfRecordProcess.setCardNo(cardNo);
            if(request.getType()==22){
                entityXfRecordProcess.setCardNo(request.getFaceToken());
            }

            //判断是否是异常单
            entityXfRecordProcess.setPayState(0);
            entityXfRecordProcess.setConsState(1);

            if (entityPersonnelInfo == null || entityPersonnelInfo.getStatus() != 0) {
                entityXfRecordProcess.setPayState(-103);
                if(entityPersonnelInfo!=null){
                    entityXfRecordProcess.setPId(entityPersonnelInfo.getPId());
                    entityXfRecordProcess.setPName(entityPersonnelInfo.getPName());
                }
            } else {
                if (entityXfAccountInfo == null || entityXfAccountInfo.getAccountState() != 0) {
                    entityXfRecordProcess.setPayState(-104);
                }
            }

            entityXfRecordProcess.setDeviceNo(request.getMachNo());
            //entiyXfRecordProcess.setCardNo(request.getAuthCode());
            if (entityPersonnelInfo != null) {
                entityXfRecordProcess.setPCode(entityPersonnelInfo.getPCode());
                entityXfRecordProcess.setPName(entityPersonnelInfo.getPName());
                entityXfRecordProcess.setDeptId(entityPersonnelInfo.getDeptId());
                EntityDeptInfo entityDeptInfo = deptInfoService.selectDeptName(request.getCompanyId(), entityPersonnelInfo.getDeptId());
                if (entityDeptInfo != null) {
                    entityXfRecordProcess.setDeptName(entityDeptInfo.getDeptName());
                }
            }
            if (entityXfAccountInfo != null) {
                entityXfRecordProcess.setAccTypeId(entityXfAccountInfo.getAccTypeId());
                entityXfRecordProcess.setAccountNo(entityXfAccountInfo.getAccountNo());
                entityXfRecordProcess.setPId(entityXfAccountInfo.getPId());
            }

            //判断消费时间段
            Date consTime = DateUtils.getDate(request.getTradeTime(), DateUtils.YYYY_MM_DD_HH_MM_SS);
            Date newDate = new Date();
            entityXfRecordProcess.setCreateTime(newDate);
            entityXfRecordProcess.setConsTime(consTime);
            entityXfRecordProcess.setMonthValue(DateUtils.getStrDate(newDate, "yyyyMM"));
            //查询收费的和商家信息
            payHandleFunService.relatedDevice(entityXfRecordProcess, request.getCompanyId(), request.getMachNo(), consTime);
            entityXfRecordProcess.setMealDate(DateUtils.getDate(DateUtils.getStrDate(consTime, DateUtils.YYYY_MM_DD), DateUtils.YYYY_MM_DD));

            //非用户异常单处理
            if (entityXfRecordProcess.getPayState()!=-103 && entityXfRecordProcess.getPayState()!=-104) {
                EntityXfRecordProcess processTradeNo = xfRecordProcessService.selectTradeNo(request.getCompanyId(), request.getTradeNo(), request.getMachNo());
                if (processTradeNo != null) {
                    if (processTradeNo.getPayState() == 1) {
                        entityXfRecordProcess.setPayState(-102);
                    }
                }
               // 在线已成功：pay_state = -102
            }

            if (request.getAmount() < 0) {
                entityXfRecordProcess.setConsMoney(request.getAmount().longValue());
                entityXfRecordProcess.setPayState(-110);
            }

            if (entityXfRecordProcess.getPayState() == -103 || entityXfRecordProcess.getPayState() == -104
                    || entityXfRecordProcess.getPayState() == -102 || entityXfRecordProcess.getPayState() == -110) {
                try {
                    if (entityXfRecordProcess.getPayState() == null) {
                        //支付状态；0支付中、1支付成功，2支付失败，3撤单中，4已撤单，5退款中，6已退款，7部分退款成功
                        entityXfRecordProcess.setPayState(0);
                    }
                    int i = xfRecordProcessService.insertEntityXfRecord(entityXfRecordProcess.getComId(), entityXfRecordProcess);
                    if (i <= 0) {
                        log.info("请求方式154:【{}】,机器号:【{}】,请求参数:【{}】,返回:【{}】", "支付请求（保存离线消费记录）", entityXfRecordProcess.getDeviceNo(), entityXfRecordProcess, ResultUtil.error(ResultEnum.Err_802));
                        //订单号重复
                        return ResultUtil.error(ResultEnum.Err_4002);
                    }
                } catch (Exception e) {
                    Throwable cause = e.getCause();
                    if (cause instanceof java.sql.SQLIntegrityConstraintViolationException) {
                        //错误信息
                        String errMsg = ((java.sql.SQLIntegrityConstraintViolationException) cause).getMessage();
                        //根据约束名称定位是那个字段
                        if (StringUtils.isNotBlank(errMsg) && errMsg.indexOf("order_no") != -1) {
                            return ResultUtil.success("订单号重复");
                        }
                    }
                    StackTraceElement ste = e.getStackTrace()[0];
                    log.info("请求方式155:【{}】,机器号:【{}】,入库新增等待表的数据4:【{}】,异常的返回:【{}】,行号:【{}】", "支付请求（保存离线消费记录）", entityXfRecordProcess.getDeviceNo(), entityXfRecordProcess, e, ste.getLineNumber());
                    log.info("请求方式156:【{}】,机器号:【{}】,请求参数:【{}】,返回:【{}】", "支付请求（保存离线消费记录）", entityXfRecordProcess.getDeviceNo(), entityXfRecordProcess, ResultUtil.error(ResultEnum.Err_900));
                    //订单号重复
                    return ResultUtil.error(ResultEnum.Err_4003);
                }
                //2023年11月14日17:25:52 菜品缓存表
                try {
                    if (request.getMenuData() != null && request.getMenuData().size() > 0) {
                        List<EntityXfGoodsListProcess> entityXfGoodsListProcesses = new ArrayList<>();
                        if (entityXfRecordProcess.getMerchId() == null) entityXfRecordProcess.setMerchId(0l);
                        if (entityXfRecordProcess.getDeptId() == null) entityXfRecordProcess.setDeptId(0l);
                        if (entityXfRecordProcess.getPId() == null) entityXfRecordProcess.setPId(0l);
                        for (MachMealDataVo menuDataVo : request.getMenuData()) {
                            EntityXfGoodsListProcess entityXfGoodsListProcess = new EntityXfGoodsListProcess();
                            entityXfGoodsListProcess.setComId(entityXfRecordProcess.getComId());
                            entityXfGoodsListProcess.setDeviceNo(entityXfRecordProcess.getDeviceNo());
                            entityXfGoodsListProcess.setPointId(0);
                            entityXfGoodsListProcess.setMerchId(0);
                            entityXfGoodsListProcess.setPId(entityXfRecordProcess.getPId().longValue());
                            entityXfGoodsListProcess.setDeptId(0);
                            entityXfGoodsListProcess.setReceiptId(0);
                            entityXfGoodsListProcess.setReceiptName("");
                            entityXfGoodsListProcess.setOrderNo(entityXfRecordProcess.getOrderNo());
                            entityXfGoodsListProcess.setConsTime(DateUtils.strToDate3(menuDataVo.getEtime(), "yyyyMMddHHmmss"));
                            entityXfGoodsListProcess.setMealDate(new Date());
                            entityXfGoodsListProcess.setMealNo(0);
                            entityXfGoodsListProcess.setConsType(request.getConsType());
                            entityXfGoodsListProcess.setIfRefund(0);
                            entityXfGoodsListProcess.setDishesId(menuDataVo.getDishesId());
                            entityXfGoodsListProcess.setDishesName(menuDataVo.getDishesName());
                            entityXfGoodsListProcess.setPriceMode(menuDataVo.getPriceMode());
                            entityXfGoodsListProcess.setWeightNumber(menuDataVo.getNum());
                            entityXfGoodsListProcess.setDishesPrice(menuDataVo.getPrice());
                            entityXfGoodsListProcess.setMonthValue(entityXfRecordProcess.getMonthValue());
                            entityXfGoodsListProcess.setCreateTime(new Date());

                            entityXfGoodsListProcesses.add(entityXfGoodsListProcess);
                        }
                        xfGoodsListProcessService.addXfGoodsListProcessList(entityXfRecordProcess.getComId(), entityXfGoodsListProcesses);
                    }
                } catch (Exception e) {
                    StackTraceElement ste = e.getStackTrace()[0];
                    log.info("请求方式257:【{}】,机器号:【{}】,入库菜品缓存表的数据:【{}】,异常的返回:【{}】,行号:【{}】", "支付请求（保存离线消费记录）", entityXfRecordProcess.getDeviceNo(), entityXfRecordProcess, e, ste.getLineNumber());
                    log.info("请求方式258:【{}】,机器号:【{}】,请求参数:【{}】,返回:【{}】", "支付请求（保存离线消费菜品记录）", entityXfRecordProcess.getDeviceNo(), entityXfRecordProcess, ResultUtil.error(ResultEnum.Err_900));
                }

                return ResultUtil.success();

            }

            //判断是否有补缴
            EntityXfRepairpayConfig entityXfRepairpayConfig = xfRepairpayConfigService.getByComId(request.getCompanyId(),entityXfRecordProcess.getMerchId());;


            Integer intMealNo = 0;
            if (entityXfRecordProcess.getMealNo() != null) {
                intMealNo = Integer.valueOf(entityXfRecordProcess.getMealNo());
            }

            //判断扣款
            //计算金额
            int consMoney = -request.getAmount();
            entityXfRecordProcess.setConsMoney(Long.valueOf(consMoney));
            int discount = xfDiscountConfigServcie.selectSiscount(request.getCompanyId(), entityXfAccountInfo.getPId(),
                    entityXfAccountInfo.getAccTypeId(), request.getConsType(), consTime, intMealNo, request.getAmount(), entityXfRecordProcess);
            consMoney = entityXfRecordProcess.getConsMoney().intValue();
            int realMoney = consMoney + discount;
            //Long chargeBalance=realMoney+entityXfAccountInfo.getAccountRechargeMoney();

            //entiyEntiyXfRecordProcess.setChargeMoney(Long.valueOf(realMoney));
            //entiyEntiyXfRecordProcess.setSubMoney(0L);

            entityXfRecordProcess.setConsType(request.getConsType());
            EntityXfDeviceMealConfig mealConfig = null;
            //5A、如果设备餐段参数中消费类型、餐段匹配的消费券方式为1-记次模式：
            String mealNoEntiy = "0";
            if (entityXfRecordProcess.getMealNo() != null) {
                mealNoEntiy = entityXfRecordProcess.getMealNo();
            }
            if (entityXfRecordProcess.getXfDeviceMealConfigList() != null) {
                for (EntityXfDeviceMealConfig entityXfDeviceMealConfig : entityXfRecordProcess.getXfDeviceMealConfigList()) {
                    String mealNo = String.valueOf(entityXfDeviceMealConfig.getMealNo());
                    if (entityXfRecordProcess.getConsType().compareTo(entityXfDeviceMealConfig.getConsType()) == 0 && mealNoEntiy.equals(mealNo)) {
                        if (entityXfDeviceMealConfig.getVoucherMode() == 1) {
                            entityXfRecordProcess.setOpTypeDiff(0L);
                        }
                        mealConfig = entityXfDeviceMealConfig;
                        break;
                    }
                }
            }
            entityXfRecordProcess.setDiscount(Long.valueOf(discount));
            entityXfRecordProcess.setRealMoney(Long.valueOf(realMoney));
            entityXfRecordProcess.setPayAmount(Long.valueOf(Math.abs(realMoney)));

            //查询扣款顺序
            EntityConsTypeConfig entityConsTypeConfig = consTypeConfigService.selectEntityConsTypeConfig(request.getCompanyId(), request.getConsType());

            int payState = 0;

            //非计次消费
            if ((mealConfig == null || mealConfig.getVoucherMode() != 1 && realMoney!=0 ) && request.getType()!=22) {


                if (entityXfRecordProcess.getRealMoney() == 0l) {
                    entityConsTypeConfig.setSubAccount(0);
                    payState =  payFunService.useVoucherAndSubAccount(entityXfRecordProcess,
                            entityConsTypeConfig,
                            mealConfig,
                            request.getMenuData(), null, entityXfAccountInfo, null);
                }else{
                    EntityXfSubAccountList entityXfSubAccountList = null;
                    Integer walletBalance = entityXfAccountInfo.getAccountRechargeMoney().intValue() + entityXfAccountInfo.getAccountSubsidyMoney().intValue();
                    if (entityConsTypeConfig.getSubAccount() == 0) {
                        entityXfRecordProcess.setOpTypeDiff(100l);
                        if (CommonUtil.isNull(entityConsTypeConfig.getWalletSerial())) walletBalance = 0;
                        if (entityConsTypeConfig.getWalletSerial().equals("1"))
                            walletBalance = entityXfAccountInfo.getAccountRechargeMoney().intValue();
                        if (entityConsTypeConfig.getWalletSerial().equals("2"))
                            walletBalance = entityXfAccountInfo.getAccountSubsidyMoney().intValue();
                    } else {
                        entityXfRecordProcess.setOpTypeDiff(100l + entityConsTypeConfig.getSubAccount());
                        entityXfSubAccountList = xfSubAccountListService.getUserSubAccount(
                                entityXfRecordProcess.getComId(),
                                entityXfRecordProcess.getPId(),
                                entityConsTypeConfig.getSubAccount()
                        );
                        walletBalance = entityXfSubAccountList.getAccountSubsidyMoney() + entityXfSubAccountList.getAccountRechargeMoney();
                        if (CommonUtil.isNull(entityConsTypeConfig.getWalletSerial())) walletBalance = 0;
                        if (entityConsTypeConfig.getWalletSerial().equals("1"))
                            walletBalance = entityXfSubAccountList.getAccountRechargeMoney();
                        if (entityConsTypeConfig.getWalletSerial().equals("2"))
                            walletBalance = entityXfSubAccountList.getAccountSubsidyMoney();
                    }

                    FeePlanVo feePlanVo = payFunService.getVoucherUse(entityXfRecordProcess,
                            entityConsTypeConfig,
                            mealConfig,
                            request.getMenuData(), walletBalance);

                    //补缴判断

                    //补缴
                    if(entityXfRepairpayConfig!=null && entityXfRepairpayConfig.getStatus()==1 && walletBalance.compareTo(feePlanVo.getWalletFee())<0){
                        //更新原DK 订单的 origOrderNo 和platOrderNo
                        xfRecordProcessService.updateDkRecord(request.getCompanyId(),request.getTradeNo());

                        //判断时间分钟
                        long time1 = consTime.getTime();
                        long time2 = new Date().getTime();        // 计算两个时间戳之间的差值，以毫秒为单位
                        long diff = time2 - time1;        // 将毫秒转换为秒
                        Long diffSeconds = diff / 60000;        // 将毫秒转换为分钟

                        entityXfRecordProcess.setOrigOrderNo(request.getTradeNo());
                        entityXfRecordProcess.setPlatOrderNo(entityXfRecordProcess.getOrderNo());

                        EntityXfRecordWaitpay entityXfRecordWaitpay = JSON.parseObject(JSON.toJSONString(entityXfRecordProcess),EntityXfRecordWaitpay.class);
                        if(diffSeconds.compareTo(entityXfRepairpayConfig.getDelayMinutes().longValue())<=0){
                            entityXfRecordWaitpay.setPayState(0);
                        }else{
                            entityXfRecordWaitpay.setPayState(-1);
                        }
                        entityXfRecordWaitpay.setFace(request.getFaceToken());

                        //补缴
                        boolean bo = xfRecordWaitpayService.saveXfRecordWaitpay(request.getCompanyId(),entityXfRecordWaitpay);
                        if(!bo){
                            return ResultUtil.error(ResultEnum.Err_4083);
                        }
                        if(diffSeconds.compareTo(entityXfRepairpayConfig.getDelayMinutes().longValue())<=0){
                            //代扣
                            //第三方的支付失败结果
                            JSONObject jsonObject=new JSONObject();
                            QrCardPayRequest qrCardPayRequest =new QrCardPayRequest();
                            qrCardPayRequest.setCompanyId(request.getCompanyId());
                            qrCardPayRequest.setMachNo(request.getMachNo());
                            qrCardPayRequest.setConsState(request.getConsState());
                            qrCardPayRequest.setType(0);
                            qrCardPayRequest.setMealData(request.getMenuData());
                            payState = payFunService.withholding(entityXfRecordProcess,qrCardPayRequest,entityCardInfo,jsonObject);
                            if (payState == 1  ){
                                xfRecordWaitpayService.updateXfRecordWaitpay(request.getCompanyId(),entityXfRecordWaitpay.getId(),1);
                            }else if(payState == 2 || payState == -1 || payState == -2  ){
                                xfRecordWaitpayService.updateXfRecordWaitpay(request.getCompanyId(),entityXfRecordWaitpay.getId(),-1);
                            }else{
                                xfRecordWaitpayService.updateXfRecordWaitpay(request.getCompanyId(),entityXfRecordWaitpay.getId(),0);
                            }
                        }else{
                            xfRecordWaitpayService.updateXfRecordWaitpay(request.getCompanyId(),entityXfRecordWaitpay.getId(),-1);

                            entityXfRecordProcess.setPayState(0);
                            xfRecordProcessService.insertEntityXfRecord(request.getCompanyId(),entityXfRecordProcess);
                        }

                        EntityXfRecordWaitpay entityXfRecordWaitpay1 = xfRecordWaitpayService.getRepairPaySum(request.getCompanyId(),entityXfRecordProcess.getPId());
                        if(entityXfRepairpayConfig.getAllowMoney()!= null
                                && entityXfRepairpayConfig.getAllowMoney()>0){
                            if(entityXfRecordWaitpay1!=null && entityXfRecordWaitpay1.getAmount().compareTo(entityXfRepairpayConfig.getAllowMoney())>=0){
                                EntityXfAccountInfo entityXfAccountInfo2 =new EntityXfAccountInfo();
                                entityXfAccountInfo2.setId(entityXfAccountInfo.getId());
                                entityXfAccountInfo2.setComId(request.getCompanyId());
                                entityXfAccountInfo2.setPId(entityXfRecordProcess.getPId());
                                entityXfAccountInfo2.setAccountState(1);
                                payConfigClientService.UpdateXFAccount(entityXfAccountInfo2);
                            }
                        }
                        return ResultUtil.success();

                    }

                    payState =  payFunService.useVoucherAndSubAccount(entityXfRecordProcess,
                            entityConsTypeConfig,
                            mealConfig,
                            request.getMenuData(), feePlanVo, entityXfAccountInfo, entityXfSubAccountList);
                }


            } else if(request.getType()!=22) {
                //计次消费
                entityXfRecordProcess.setOpTypeDiff(0l);
                entityXfRecordProcess.setChargeMoney(0L);
                entityXfRecordProcess.setSubMoney(0L);
                entityXfRecordProcess.setSubBalance(entityXfAccountInfo.getAccountSubsidyMoney());
                entityXfRecordProcess.setChargeBalance(entityXfAccountInfo.getAccountRechargeMoney());
                entityConsTypeConfig.setSubAccount(0);
                payState =  payFunService.useVoucherAndSubAccount(entityXfRecordProcess,
                        entityConsTypeConfig,
                        mealConfig,
                        request.getMenuData(), null, entityXfAccountInfo, null);

            }else if(request.getType()==22){

                JSONObject jsonObject=new JSONObject();
                QrCardPayRequest qrCardPayRequest =new QrCardPayRequest();
                qrCardPayRequest.setCompanyId(request.getCompanyId());
                qrCardPayRequest.setMachNo(request.getMachNo());
                qrCardPayRequest.setConsState(request.getConsState());
                qrCardPayRequest.setType(22);
                qrCardPayRequest.setMealData(request.getMenuData());
                qrCardPayRequest.setFaceToken(request.getFaceToken());
                payState = payFunService.withholding(entityXfRecordProcess,qrCardPayRequest,entityCardInfo,jsonObject,2);
                if (payState != 1) {
                    try {
                        if (entityXfRecordProcess.getPayState() == null) {
                            //支付状态；0支付中、1支付成功，2支付失败，3撤单中，4已撤单，5退款中，6已退款，7部分退款成功
                            entityXfRecordProcess.setPayState(0);
                        }
                        int i = xfRecordProcessService.insertEntityXfRecord(entityXfRecordProcess.getComId(), entityXfRecordProcess);
                        if (i <= 0) {
                            log.info("请求方式154离线:【{}】,机器号:【{}】,请求参数:【{}】,返回:【{}】", "支付请求（保存离线消费记录）", entityXfRecordProcess.getDeviceNo(), entityXfRecordProcess, ResultUtil.error(ResultEnum.Err_802));
                            //订单号重复
//                            return ResultUtil.error(ResultEnum.Err_4002);
                        }
                    } catch (Exception e) {
                        StackTraceElement ste = e.getStackTrace()[0];
                        log.info("请求方式155离线:【{}】,机器号:【{}】,入库新增等待表的数据4:【{}】,异常的返回:【{}】,行号:【{}】", "支付请求（保存离线消费记录）", entityXfRecordProcess.getDeviceNo(), entityXfRecordProcess, e, ste.getLineNumber());
                        log.info("请求方式156离线:【{}】,机器号:【{}】,请求参数:【{}】,返回:【{}】", "支付请求（保存离线消费记录）", entityXfRecordProcess.getDeviceNo(), entityXfRecordProcess, ResultUtil.error(ResultEnum.Err_900));
                    }
                    payState = 1;
                }
            }

            if (payState == 1) {
                return ResultUtil.success();
            } else if (payState == -1) {
                //商户支付渠道未配置"
                return ResultUtil.error(ResultEnum.Err_3048);
            } else if (payState == -2) {
                //代扣未签约"
                return ResultUtil.error(ResultEnum.Err_3047);
            } else if (payState == -11) {
                //订单号重复
                return ResultUtil.error(ResultEnum.Err_802);
            } else if (payState == -12) {
                //余额不足
                return ResultUtil.error(ResultEnum.Err_4024);
            } else {
                //支付结果未知
                return ResultUtil.error(ResultEnum.Err_3029);
            }

        } catch (ParseException e) {
            StackTraceElement ste = e.getStackTrace()[0];
            log.info("请求方式262:【{}】,机器号:【{}】,离线记录上传异常:【{}】,异常的返回:【{}】,行号:【{}】", "支付请求（保存离线消费记录）", request.getMachNo(), entityXfRecordProcess, e, ste.getLineNumber());
            return ResultUtil.error(ResultEnum.Err_4003);
        }
    }


    /**
     * 获取微信公话参数
     */
    @PostMapping(value = PayHandleUrl.URL_getWxGhParam)
    public Result getWxGhParam(@RequestBody GetWxGhParamRequest request) {
        EntityXfRecordProcess entityXfRecordProcess = new EntityXfRecordProcess();
        entityXfRecordProcess.setPointId(0l);
        payHandleFunService.relatedDevice(entityXfRecordProcess, request.getCompanyId(), request.getDeviceNo(), new Date());

        JSONObject jsonObject = new JSONObject();
        jsonObject.put("appId","");
        jsonObject.put("appKey","");
        jsonObject.put("productId","");
        jsonObject.put("keyVersion","");
        jsonObject.put("signature","");
        jsonObject.put("miniAppid","");
        jsonObject.put("modelId","");
        jsonObject.put("snTicket","");
        jsonObject.put("deviceName",entityXfRecordProcess.getDeviceName());

        if (request.getType() == 2 || request.getType() == 3) {
            EntityWechatAppInfo entityWechatAppInfo = wechatAppInfoService.getInfo(request.getCompanyId(), 0l, "xcx");
            if (entityWechatAppInfo != null) {
                jsonObject.put("miniAppid",entityWechatAppInfo.getAppid());
                jsonObject.put("modelId",entityWechatAppInfo.getAlipayAes());

                String canKey = "xcxToken:" + request.getCompanyId()+":"+entityWechatAppInfo.getAppid();
                Object tokenRedis = redisUtil.get(canKey);
                if (tokenRedis == null) {
                    tokenRedis = WxGhUtils.getAccessToken(entityWechatAppInfo.getAppid(),entityWechatAppInfo.getAppsecret());
                    if(tokenRedis!=null){
                        redisUtil.set(canKey,tokenRedis,7000l);
                    }
                }
                if(tokenRedis!=null){
                    String snTicket = WxGhUtils.getSnTicket((String)tokenRedis,entityWechatAppInfo.getAlipayAes(),request.getDeviceNo());
                    if(snTicket!=null){
                        jsonObject.put("snTicket",snTicket);
                    }
                }
            }
        }
        if (request.getType() == 1 || request.getType() == 3) {
            EntityWechatAppInfo entityWechatAppInfo = wechatAppInfoService.getInfo(0l, -200l, "mach");
            if(entityWechatAppInfo!=null){
                jsonObject.put("appId",entityWechatAppInfo.getAppid());
                jsonObject.put("appKey",entityWechatAppInfo.getAppsecret());

                JSONObject jsonObject1 =JSON.parseObject(entityWechatAppInfo.getAlipayPublicKey());
                jsonObject.put("productId",jsonObject1.get("productId"));
                jsonObject.put("keyVersion",jsonObject1.get("keyVersion"));

                String productId = jsonObject1.getString("productId");
                String deviceId = request.getDeviceNo();
                // TODO 上传公钥到「微信终端合作平台」
                // 获取Signature
                String signature = WmpfDeviceSignUpUtil.getSignature(
                        productId,
                        deviceId,
                        entityWechatAppInfo.getAppPrivateKey()
                );
                log.info("微信公话获取签名 【{}】",signature);
                jsonObject.put("signature",signature);
            }
        }

        return ResultUtil.success(jsonObject);
    }


}
